<?php

class ModelWxappLycShopnew extends Model {

	//获取附近商铺
	public function getShopInfo($filter){

		$lat = $filter['lat'];
		$lng = $filter['lng'];
		$inshop_id = $filter['inshop_id'];
		$sort = $filter['sort'];
		$sortway = $filter['sortway'];
		$search = $filter['search'];

		if($sort && $sortway){
			$orderby = " ORDER BY ".$sort." ".$sortway;
		}
		else{
			$orderby = "";
		}
		
		$distance = "acos(cos(".$lat."*pi()/180 )*cos(s.lat*pi()/180)*cos(".$lng."*pi()/180 -s.lng*pi()/180)+sin(".$lat."*pi()/180 )*sin(s.lat*pi()/180))*6370996.81/1000"; //计算距离

		$where = "s.lat != 0 AND (s.status = 2 OR s.status = 3) ";
		$sql = "SELECT 
		convert(".$distance.",decimal(11,2))  as distance, 
		s.*, 
		count(sc.shop_id) as visitnum
		FROM shop s 
		LEFT JOIN shop_concern sc on s.shop_id = sc.shop_id 
		WHERE ".$where." 
		GROUP BY s.shop_id";
		$sql .= $orderby." LIMIT 0,20";

		$query = $this->db->query($sql);
		foreach ($query->rows as &$v) {
			
			//筛选商品
			if($search != ''){
				$count = $this->getSearchProducts($v['shop_id'],$search);
				if($count < 1){
					continue;
				}
			}

			$shopinfo[] = array(
				'logo'=>$this->getShopLogo($v['shop_id']),
				'image'=>$this->getShopImage($v['shop_id']),
				'distance'=>$v['distance'],
				'shop_id'=>$v['shop_id'],
				'shop_name'=>$v['shop_name'],
				'customer_id'=>$v['customer_id'],
				'shop_describe'=>$v['shop_describe'],
				'discount_message'=>$v['discount_message'],
				'level'=>(int)$v['level'],
				'address'=>$v['address'],
				'country_id'=>$v['country_id'],
				'country'=>$v['country'],
				'zone_id'=>$v['zone_id'],
				'zone'=>$v['zone'],
				'city_id'=>$v['city_id'],
				'city'=>$v['city'],
				'status'=>$v['status'],
				'date_added'=>$v['date_added'],
				'telephone'=>$v['telephone'],
				
				'shelf_num'=>$v['shelf_num'],
				'visitnum'=>$v['visitnum'],
				'shelf'=>$this->getShelfImage($v['shop_id']),
				'products'=>$this->getShopProducts($v['shop_id']),
				'isconcern' =>$this->checkConcern($v['shop_id'],$inshop_id),
			);

		}

		return $shopinfo;
		 
	}

	//获取商铺logo
	public function getShopLogo($shop_id){
		$sql = "SELECT u.filename FROM customer_images ci LEFT JOIN upload u ON ci.`customer_images_id` = u.`customer_images_id` where (ci.type=1 OR ci.type=3) AND ci.shop_id=".$shop_id." ORDER BY ci.type DESC LIMIT 0,1";
		$result = $this->db->query($sql)->row;
		$image = 'http://m.bhz360.com/system/storage/upload/'.$result['filename'];
		return $image;
	}

	//获取商铺照片
	public function getShopImage($shop_id){
		$sql = "SELECT u.filename FROM customer_images ci LEFT JOIN upload u ON ci.`customer_images_id` = u.`customer_images_id` where ci.type=1 AND ci.shop_id=".$shop_id." ORDER BY ci.type DESC LIMIT 0,1";
		$result = $this->db->query($sql)->row;
		$image = 'http://m.bhz360.com/system/storage/upload/'.$result['filename'];
		return $image;
	}

	//获取货架照片
	public function getShelfImage($shop_id){
		$where['shop_id'] = $shop_id;
		$where['status'] = 1;
		$temp = M('shelf')
			->where($where)
			->Field('shelf_image,shelf_id')->find();
		$result = array(
			'shelf_id' => $temp['shelf_id'],
			'image' => "http://m.bhz360.com/system/storage/upload/".$temp['shelf_image']
		);

		return $result;
	}
	
	//获取商品图片
	public function getShopProducts($shop_id){
		$this->load->model('tool/image');

		$sql  = "SELECT sp.shop_product_id, sp.product_class1, sp.product_class2, sp.product_class3, sp.shop_basic_code, sp.sku, sp.price, sp.sale_price, sp.`status`, sp.date_added, sp.shop_id, sp.shelf_id, sp.`name`, sp.description, sp.product_id, sp.image FROM shop_product AS sp WHERE sp.shop_id = ".$shop_id." LIMIT 0,4";
		$query = $this->db->query($sql);
		// var_dump($query->rows);die();

		foreach ($query->rows as $v) {
			if ($v['image'] != null && file_exists(DIR_IMAGE . $v['image'])) {
				$image = $this->model_tool_image->resize($v['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
			}
			else {
				continue;
				$image = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
			}
			$products[] = array(
				'shop_product_id'=>$v['shop_product_id'],
				// 'product_id'=>$v['product_id'],
				// 'product_code'=>$v['product_code'],
				'image'=>$image,
			);
		}

		return $products;
	}
	
	//全文搜索商品
	public function getSearchProducts($shop_id,$search){

		$keyword = trim($search);

		/*全文搜索*/
		require_once(DIR_SYSTEM . 'xunsearch/php/lib/XS.php');

		$xs = new XS('wxapp');

		$search = $xs->search;   //获取搜索对象		
		$search->setFuzzy(true);	 //模糊搜索
		$search->setLimit(10000,0);

		$products = $search->setAutoSynonyms()->setQuery($keyword)->setFacets(array('shop_id'))->search();  //搜索
		$temp = $search->getFacets('shop_id');
		
		$result = 0;
		foreach($temp as $v => $count){
			if($v == $shop_id){
				$result = $count;
			}
		}

		return $result;

	}

	//获取是否关注商铺
	public function checkConcern($shop,$customer){
		$where['shop_id'] = $shop;
		$where['customer_in_shop_id'] = $customer;
		$result = M('shop_concern')->where($where)->getField('status');

		if($result == ""){
			$result = 0;
		}

		return $result;
	}

		//根据id获取商铺信息+全部商品
	public function getshopProductsById($filter){
		
		$inshop_id = $filter['customer_in_shop_id'];
		$where['s.shop_id'] = $filter['shop_id'];
		$result = M('shop')
			->alias('s')
			->join('shop_concern sc on s.shop_id = sc.shop_id','left')
			->where($where)
			->field('s.*, count(sc.shop_id) as visitnum')
			->select();

		foreach($result as $v){
			$shopinfo = array(
				'logo'=>$this->getShopLogo($v['shop_id']),
				'image'=>$this->getShopImage($v['shop_id']),
				'shop_id'=>$v['shop_id'],
				'shop_name'=>$v['shop_name'],
				'customer_id'=>$v['customer_id'],
				'shop_describe'=>$v['shop_describe'],
				'discount_message'=>$v['discount_message'],
				'level'=>(int)$v['level'],
				'address'=>$v['address'],
				'country_id'=>$v['country_id'],
				'country'=>$v['country'],
				'zone_id'=>$v['zone_id'],
				'zone'=>$v['zone'],
				'city_id'=>$v['city_id'],
				'city'=>$v['city'],
				'status'=>$v['status'],
				'date_added'=>$v['date_added'],
				'telephone'=>$v['telephone'],
				
				'shelf_num'=>$v['shelf_num'],
				'visitnum'=>$v['visitnum'],
				'products'=>$this->getProductsById($v['shop_id']),
				'isconcern' =>$this->checkConcern($v['shop_id'],$inshop_id),
			);
		}

		return $shopinfo;

	}

	public function getProductsById($shop_id){
		$sql = "SELECT shop_product.shop_product_id, shop_product.product_class1, shop_product.product_class2, shop_product.product_class3, shop_product.shop_basic_code, shop_product.sku, shop_product.price, shop_product.sale_price, shop_product.`status`, shop_product.date_added, shop_product.shop_id, shop_product.shelf_id, shop_product.`name`, shop_product.product_id, shop_product.image FROM `shop_product` where shop_id =".$shop_id.' order by shop_product.`status` DESC limit 0,500';
			// echo $sql;
		$query = $this->db->query($sql);
		 foreach ($query->rows as $key => $value) {

		 	$this->load->model('tool/image');
			if ($value['image'] != null && file_exists(DIR_IMAGE . $value['image'])) {
				$value['image'] = $this->model_tool_image->resize($value['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
			}
			else {
				$value['image'] = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
			}
			$res[] = array(
				'shop_product_id'=>$value['shop_product_id'],
				'sku'=>$value['sku'],
				'price'=>$value['price'],
				'status'=>$value['status'],
				'shop_id'=>$value['shop_id'],
				'sale_price'=>$value['sale_price'],
				'name'=>$value['name'],
				'image'=>$value['image'],
			);
		 }
		 return $res;

	}

	//根据id获取商铺信息
	public function getShopInfoById($filter){
		
		$inshop_id = $filter['customer_in_shop_id'];
		$where['s.shop_id'] = $filter['shop_id'];
		$result = M('shop')
			->alias('s')
			->join('shop_concern sc on s.shop_id = sc.shop_id','left')
			->where($where)
			->field('s.*, count(sc.shop_id) as visitnum')
			->select();

		foreach($result as $v){
			$shopinfo = array(
				'logo'=>$this->getShopLogo($v['shop_id']),
				'image'=>$this->getShopImage($v['shop_id']),
				'shop_id'=>$v['shop_id'],
				'shop_name'=>$v['shop_name'],
				'customer_id'=>$v['customer_id'],
				'shop_describe'=>$v['shop_describe'],
				'discount_message'=>$v['discount_message'],
				'level'=>(int)$v['level'],
				'address'=>$v['address'],
				'country_id'=>$v['country_id'],
				'country'=>$v['country'],
				'zone_id'=>$v['zone_id'],
				'zone'=>$v['zone'],
				'city_id'=>$v['city_id'],
				'city'=>$v['city'],
				'status'=>$v['status'],
				'date_added'=>$v['date_added'],
				'telephone'=>$v['telephone'],
				
				'shelf_num'=>$v['shelf_num'],
				'visitnum'=>$v['visitnum'],
				'shelf'=>$this->getShopShelf($v['shop_id']),
				'isconcern' =>$this->checkConcern($v['shop_id'],$inshop_id),
			);
		}

		return $shopinfo;

	}

	//获取商铺货架信息
	public function getShopShelf($shop_id){
		$where['shop_id'] = $shop_id;
		$where['status'] = 1;
		$temp = M('shelf')
			->alias('s')
			->join('shelf_map sm on s.shelf_id = sm.shelf_id','left')
			->join('category_description cd on s.shelf_category = cd.category_id','left')
			->where($where)
			->field('s.*, cd.name as category, sm.shelf_map_id as shelf_no')
			->select();
		foreach($temp as $v){
			
			$shelf_x = M('shelf_product')->where('shelf_id='.$v['shelf_id'])->order('layer_position desc')->limit(1)->getField('layer_position');
			$shelf_y = M('shelf_product')->where('shelf_id='.$v['shelf_id'])->order('shelf_layer desc')->limit(1)->getField('shelf_layer');
			
			//热门商品
			$hot = $this->getHotProduct($v['shelf_id']);

			$shopshelf[] = array(
				'shelf_id' => $v['shelf_id'],
				'shelf_name' => $v['shelf_name'],
				'shelf_no' => $v['shelf_no'],
				'category' => $v['category'],
				'xy' => $shelf_y."排".$shelf_x."列",
				'image' => "http://m.bhz360.com/system/storage/upload/".$v['shelf_image'],

				'hotname' => $hot['name'],
				'hotimage' => $hot['image'],
				'hotid' => $hot['shop_product_id']
			);
		}

		return $shopshelf;
	}
	
	//根据货架id获取热门商品
	public function getHotProduct($shelf_id){
		
		$where['sp.shelf_id'] = $shelf_id;
		$result = M('shelf_product')
			->alias('sp')
			->join('shop_product shp on sp.shop_product_id = shp.shop_product_id','left')
			->where($where)
			->field('shp.*,sp.*')
			->find();

		$this->load->model('tool/image');
		if ($result['image'] != null && file_exists(DIR_IMAGE . $result['image'])) {
			$result['image'] = $this->model_tool_image->resize($result['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
		}
		else {
			$result['image'] = $this->model_tool_image->resize('no_image.jpg', $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
		}

		return $result;

	}
	
	//根据id获取商铺货架信息
	public function getShelfById($filter){

		$where['sp.shelf_id'] = $filter['shelf_id'];
		$result = M('shelf_product')
			->alias('sp')
			->join('shop_product shp on sp.shop_product_id = shp.shop_product_id','left')
			->where($where)
			->field('sp.layer_position as shelf_x, sp.shelf_layer as shelf_y, shp.*')
			->select();

		return $result;

	}

	//获取店铺购物车
	public function getCart($filter){
		$where['sc.shop_id'] = $filter['shop_id'];
		$where['sc.customer_in_shop_id'] = $filter['customer_in_shop_id'];
		$where['shp.shop_id'] = $filter['shop_id'];
		$result = M('shop_cart')
			->alias('sc')
			->join('shop_product shp on sc.shop_product_id = shp.shop_product_id','left')
			->where($where)
		->field('sc.cart_id as cart_id,sc.customer_in_shop_id as customer_in_shop_id,sc.quantity as quantity,sc.shop_product_id as shop_product_id,shp.shop_product_id, shp.product_class1, shp.product_class2, shp.product_class3, shp.shop_basic_code, shp.sku, shp.price as originprice, shp.sale_price as saleprice, shp.`status`, shp.date_added, shp.shop_id, shp.shelf_id, shp.`name`, shp.product_id, shp.image')
		->select();
		// echo M('shop_cart')->getlastSql();

		return $result;
	}

	//店铺添加购物车
	public function addCart($filter){

		$where['shop_id'] = $filter['shop_id'];
		$where['customer_in_shop_id'] = $filter['customer_in_shop_id'];
		$where['shop_product_id'] = $filter['shop_product_id'];
		$result = M('shop_cart')->where($where)->select();

		if($result){
			return 'fail';
		}
		else{
		M('shop_cart')->add($filter);
			return 'success';
		}
	}
	
	//修改店铺购物车数量
	public function updateCart($filter){
		 $where['customer_in_shop_id'] = $filter['customer_in_shop_id'];
		 $where['shop_inventory_id'] = $filter['shop_inventory_id'];
		 $data['quantity'] = $filter['quantity'];

		 M('shop_cart')->where($where)->save($data);
	}
	
	//店铺删除购物车
	public function deleteCart($cart_id){
		$where['cart_id'] = $cart_id;
		M('shop_cart')->where($where)->delete();
	}
	
	//获取countryid
	public function getCountryId($name){
		$where['name'] = trim($name);
		$id = M('country')->where($where)->getField('country_id');
		if(!$id){
			$id = 0;
		}
		return $id;
	}

	//获取zoneid
	public function getZoneId($name){
		$where['name'] = trim($name);
		$id = M('zone')->where($where)->getField('zone_id');
		if(!$id){
			$id = 0;
		}
		return $id;
	}

	//获取cityid
	public function getCityId($name){
		$where['name'] = trim($name);
		$id = M('city')->where($where)->getField('city_id');
		if(!$id){
			$id = 0;
		}
		return $id;
	}
	
	//立即购买
	public function toBuy($filter){
		$data['payment_customer_id'] = $filter['payment_customer_id'];
		$data['shop_id'] = $filter['shop_id'];

		$data['payment_address'] = $filter['sendaddress']['address'];
		$data['payment_fullname'] = $filter['sendaddress']['name'];
		$data['payment_country'] = $filter['sendaddress']['country'];
		$data['payment_country_id'] = $this->getCountryId($filter['sendaddress']['country']);
		$data['payment_zone'] = $filter['sendaddress']['zone'];
		$data['payment_zone_id'] = $this->getZoneId($filter['sendaddress']['zone']);
		$data['payment_city'] = $filter['sendaddress']['city'];
		$data['payment_city_id'] = $this->getCityId($filter['sendaddress']['city']);
		$data['payment_telephone'] = $filter['sendaddress']['tel'];

		$data['total'] = $filter['allprice'];

		$data['payment_method'] = $filter['payname'];
		$data['payment_code'] = $filter['paycode'];

		$data['status'] = 1;
		$data['date_added'] = date('Y-m-d H:i:s');
		$data['date_modified'] = date('Y-m-d H:i:s');
		$data['is_pay'] = 0;

		$order_id = M('shop_order')->add($data);

		foreach($filter['buyList'] as $v){
			$pdata['order_id'] = $order_id;
			$pdata['shop_inventory_id'] = 0;
			$pdata['shop_product_id'] = $v['shop_product_id'];
			$pdata['name'] = $v['name'];
			$pdata['quantity'] = $v['quantity'];
			$pdata['price'] = $v['originprice'];
			$pdata['pay_price'] = $v['saleprice'];
			$pdata['total'] = $pdata['quantity']*$pdata['price'];
			$pdata['pay_total'] = $pdata['quantity']*$pdata['pay_price'];
			$pdata['status'] = 1;

			M('shop_order_product')->add($pdata);
		}
		//添加关注
		$sql = "SELECT cip.customer_in_shop_id, c.customer_id FROM customer AS c LEFT JOIN customer_in_shop AS cip ON c.wx_mp_openid = cip.open_id WHERE c.customer_id=".$filter['payment_customer_id'];
		$query = $this->db->query($sql);
		$customer_in_shop_id = $query->row['customer_in_shop_id'];

		$shop_concern = M('shop_concern')->where(array('customer_in_shop_id'=>$customer_in_shop_id,'shop_id'=>$filter['shop_id']))->find();
		if (empty($shop_concern)) {
			$datac = array(
			'shop_id'=>$filter['shop_id'],
			'customer_in_shop_id'=> $customer_in_shop_id,
			'status'=>1,
			'date_added'=>date("Y-m-d H:i:s"),
			);
			M('shop_concern')->add($datac);
		}else{
			M('shop_concern')->where(array('customer_in_shop_id'=>$customer_in_shop_id,'shop_id'=>$filter['shop_id']))->save(array('status'=>1));
			// echo M('shop_concern')->getlastSql();
		}

		


		return $order_id;

	}

	//获取客户订单
	public function getshoporder($customer_id){
		
		$where['so.payment_customer_id'] = $customer_id;
		$temp = M('shop_order')
			->alias('so')
			->join('shop s on so.shop_id = s.shop_id','left')
			->where($where)
			->field('so.*, s.shop_name as shop_name, s.country as s_country, s.city as s_city, s.zone as s_zone, s.address as s_address, s.telephone as s_telephone')
			->order('so.date_added desc')
			->select();
		
		$result[0] = array(); //无效
		$result[1] = array();  //初始
		$result[2] = array(); //已接单
		$result[3] = array(); //完成

		foreach($temp as $v){
			
			switch($v['status']){
				case 0:
					$v['status'] = '无效';
					$result[0][] = $v;
					break;
				case 1:
					$v['status'] = '初始';
					$result[1][] = $v;
					break;
				case 2:
					$v['status'] = '已接单';
					$result[2][] = $v;
					break;
				case 3:
					$v['status'] = '完成';
					$result[3][] = $v;
					break;
			}

		}

		return $result;

	}
	
	//获取商铺资金动向
	public function getShopMoney($customer_id){

		$where['customer_id'] = $customer_id;
		$shopinfo = M('shop')->where($where)->find();
		
		$where2['shop_id'] = $shopinfo['shop_id'];
		$loglist = M('shop_log')
			->alias('sl')
			->join('shop_case sc on sl.case_id = sc.case_id','left')
			->where($where2)
			->field('sl.*,sc.case_name')
			->order('sl.date_added desc')
			->select();

		$result = array(
			'shop_name' => $shopinfo['shop_name'],
			'money' => $shopinfo['money'],
			'loglist' => $loglist
		);

		return $result;

	}

	public function getShopProductById($shop_product_id){
		$sql = "SELECT sp.shop_product_id, sp.product_class1, sp.product_class2, sp.product_class3, sp.shop_basic_code, sp.sku, sp.price, sp.sale_price, sp.`status`, sp.date_added, sp.shop_id, sp.shelf_id, sp.`name`, sp.description, sp.product_id, sp.image FROM shop_product AS sp WHERE sp.shop_product_id =".$shop_product_id;
		// echo $sql;
		$query = $this->db->query($sql);
		return $query->rows;
	}

	public function getImages($shop_product_id){
		$sql = "SELECT shop_product_image.image, shop_product_image.shop_product_id FROM `shop_product_image` WHERE shop_product_image.shop_product_id =".$shop_product_id;
		// echo $sql;
		$query = $this->db->query($sql);
		return $query->rows;
	}

	public function getProduct($shop_id){
		$sql = "SELECT sp.shop_product_id, sp.product_class1, sp.product_class2, sp.product_class3, sp.shop_basic_code, sp.sku, sp.price, sp.sale_price, sp.`status`, sp.date_added, sp.shop_id, sp.shelf_id, sp.`name`, sp.description, sp.product_id, sp.image FROM shop_product AS sp where sp.shop_id = ".$shop_id;

		$query = $this->db->query($sql);
		return $query->rows;
	}


	public function getinfo($customerInShopId,$shop_id){
		
		return M('shop_concern')->where(array('customer_in_shop_id'=>$customerInShopId,'shop_id'=>$shop_id))->find();
	}
	
	public function concern($data){
		
		return M('shop_concern')->add($data);
	}

	

	public function upstatus($customerInShopId,$shop_id,$status){
		
		return M('shop_concern')->where(array('customer_in_shop_id'=>$customerInShopId,'shop_id'=>$shop_id))->save(array('status'=>$status));
	}


		//获取货架商品详细
	public function getShelfProducts($shelf_id){

		$where['sp.shelf_id'] = $shelf_id;
		$shelfProducts = M('shelf_product')
			->alias('sp')
			->join('shop_product shp on sp.shop_product_id = shp.shop_product_id','left')
			->where($where)
			->field('sp.shelf_layer,sp.layer_position,sp.min_order_qty,sp.show_qty,sp.shelf_product_id,sp.stock_qty_temp,sp.stock_qty,shp.shop_product_id, shp.product_class1, shp.product_class2, shp.product_class3, shp.shop_basic_code, shp.sku, shp.price, shp.sale_price, shp.`status`, shp.date_added, shp.shop_id, shp.shelf_id, shp.`name`, shp.product_id, shp.image')
			->select();
			// echo M('shelf_product')->getlastSql();

		return $shelfProducts;

	}

	

	public function getProductCategory($shop_id){
		$sql = "SELECT (SELECT cd.`name` FROM shop_category_description AS cd WHERE cd.category_id = sp.product_class3 ) AS product_class3name, (SELECT c.`image` FROM shop_category AS c WHERE c.category_id = sp.product_class3 ) AS image3, (SELECT c.`image` FROM shop_category AS c WHERE c.category_id = sp.product_class2 ) AS image2, sp.product_class3, sp.product_class2, (SELECT cd.`name` FROM shop_category_description AS cd WHERE cd.category_id = sp.product_class2 ) AS product_class2name FROM shop_product AS sp WHERE sp.shop_id =".$shop_id;

		$query = $this->db->query($sql);
		return $query->rows;
	}


			//获取分类商品
	public function getCategoryProducts($filter){
		$where['si.shop_id'] = $filter['shop_id'];
		$where['si.product_class3'] = $filter['category'];
		$result = M('shop_product')
			->alias('si')
			->where($where)
			->select();
		return $result;
	}
}

?>